<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use fast\Random;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 置业顾问管理
 *
 * @icon fa fa-circle-o
 */
class Canal extends Backend
{

    /**
     * Canal模型对象
     * @var \app\common\model\Canal
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Canal;
        $this->view->assign("typeDataList", $this->model->getTypeDataList());

    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(["chargeman"=>function($query){
                $query->withField('id,name');
            }])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row["connectionNum"]=\app\common\model\Connection::where(["canal_id"=>$row["id"]])->count();

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $res=$this->check($params);
        if(!$res) return $res;
        Db::startTrans();
        try {
            if(array_key_exists('avatar',$params)){
                if(!empty($params["avatar"]) && !strstr($params["avatar"],"http")) $params["avatar"]=cdnurl($params["avatar"],true);
            }
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            if($params["type_data"]==1){
                $params["pid"]=0;
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    protected function check($params){
        $data=[
            ['username', 'require', '账号不能为空'],
            ['name', 'require', '姓名不能为空'],
            ['password', 'require', '密码不能为空'],
            ['mobile', 'require|regex:1[3-9]\d{9}', '请输入手机号码|手机号码格式错误'],
        ];
        if (!empty($params["id"])){
            $data=[
                ['mobile', 'regex:1[3-9]\d{9}', '手机号码格式错误'],
            ];
        }
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        if(!empty($list) && !empty($params["id"])){
            $list=\app\common\model\Canal::field("id")->where(["username"=>$params["username"]])->find();
            $this->error('提交失败：账号已存在');
            //if($params["id"]!=$list["id"])$this->error('提交失败：账号已存在');
        }
        return true;
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $params["id"]=$row["id"];
        $res=$this->check($params);
        if(!$res) return $res;
        unset($params["id"]);
        Db::startTrans();
        try {
            if(!empty($params['password'])){
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }else{
                unset($params['password']);
            }
            if(array_key_exists('avatar',$params)){
                if(!empty($params["avatar"]) && !strstr($params["avatar"],"http")) $params["avatar"]=cdnurl($params["avatar"],true);
            }
            if($params["type_data"]==1){
                $params["pid"]=0;
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
